using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OpenPasteSpider.projectmodel;
using PasteFormHelper;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace OpenPasteSpider.bind
{

    /// <summary>
    /// 服务的镜像版本
    ///</summary>
    [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
    public class BindServiceImageAppService : OpenPasteSpiderAppService
    {

        private IOpenPasteSpiderDbContext _dbContext;
        public BindServiceImageAppService(IOpenPasteSpiderDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PagedResultDto<BindServiceImageListDto>> GetListAsync(int page = 1, int size = 20)
        {

            var query = _dbContext.BindServiceImage.Where(t => 1 == 1).OrderByDescending(xy => xy.Id);
            var pagedResultDto = new PagedResultDto<BindServiceImageListDto>();
            //pagedResultDto.TotalCount = await query.CountAsync();
            //var userList = await query.Page(page, size).ToListAsync();
            //var temList = ObjectMapper.Map<List<BindServiceImage>, List<BindServiceImageListDto>>(userList);
            //pagedResultDto.Items = temList;

            var list = from a in _dbContext.BindServiceImage
                       join b in _dbContext.ServiceInfo on a.ServiceId equals b.Id into c
                       from d in c.DefaultIfEmpty()
                       select new BindServiceImageListDto
                       {
                           Id = a.Id,
                           CreateDate = a.CreateDate,
                           BuildState = a.BuildState,
                           ImageDigest = a.ImageDigest,
                           IsEnable = a.IsEnable,
                           Service = new ServiceInfoDto()
                           {
                               Name = d.Name
                           },
                           ServiceId = a.ServiceId,
                           StoreId = a.StoreId,
                           Version = a.Version
                       };

            pagedResultDto.TotalCount = await list.CountAsync();

            pagedResultDto.Items = await list.OrderBy(x => x.Id).Page(page, size).ToListAsync();

            return pagedResultDto;
        }

        /// <summary>
        /// 根据ID获取单项服务的镜像版本
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public BindServiceImageDto GetByIdAsync(int id)
        {
            var query = _dbContext.BindServiceImage.Where(t => t.Id == id).FirstOrDefault();
            var temList = ObjectMapper.Map<BindServiceImage, BindServiceImageDto>(query);
            return temList;
        }

        /// <summary>
        /// 根据ID获取待更新单项信息服务的镜像版本
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public BindServiceImageUpdateDto GetInfoForUpdateAsync(int id)
        {
            var query = _dbContext.BindServiceImage.Where(t => t.Id == id).FirstOrDefault();
            var temList = ObjectMapper.Map<BindServiceImage, BindServiceImageUpdateDto>(query);
            return temList;
        }


        /// <summary>
        /// 添加一个服务的镜像版本
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<BindServiceImageDto> CreateItemAsync(BindServiceImageAddDto input)
        {

            var newu = ObjectMapper.Map<BindServiceImageAddDto, BindServiceImage>(input);
            newu.IsEnable = true; newu.CreateDate = DateTime.Now;            //添加自定义
            _dbContext.Add(newu);
            await _dbContext.SaveChangesAsync();
            //var updated = await _repository.InsertAsync(newu,true);
            var backinfo = ObjectMapper.Map<BindServiceImage, BindServiceImageDto>(newu);
            return backinfo;
        }
        /// <summary>
        /// 更新一个服务的镜像版本
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<BindServiceImageDto> UpdateItemAsync(BindServiceImageUpdateDto input)
        {
            var info = await _dbContext.BindServiceImage.Where(x => x.Id == input.Id).FirstOrDefaultAsync();
            if (info == null || info == default)
            {
                throw new UserFriendlyException("需要查询的信息不存在", "404");
            }
            ObjectMapper.Map<BindServiceImageUpdateDto, BindServiceImage>(input, info);
            //var updated = await _repository.UpdateAsync(newu);
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<BindServiceImage, BindServiceImageDto>(info);
            return backinfo;
        }
        
        /// <summary>
        /// 读取AddDto的数据模型 用于新增
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public VoloModelInfo ReadAddModel()
        {
            var _model = PasteBuilderHelper.ReadModelProperty<BindServiceImageAddDto>(new BindServiceImageAddDto());
            return _model;
        }

        /// <summary>
        /// 读取Dto的数据模型 用于更新
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public async Task<VoloModelInfo> ReadUpdateModel(int id)
        {
            var _info = await _dbContext.BindServiceImage.Where(x => x.Id == id).AsNoTracking().FirstOrDefaultAsync();
            if (_info == null || _info == default)
            {
                throw new PasteCodeException("查询的信息不存在，无法执行编辑操作！");
            }
            var dto = ObjectMapper.Map<BindServiceImage, BindServiceImageUpdateDto>(_info);
            var _dataModel = PasteBuilderHelper.ReadModelProperty<BindServiceImageUpdateDto>(dto);
            return _dataModel;
        }

        /// <summary>
        /// 读取Dto的数据模型 用于查看详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public async Task<VoloModelInfo> ReadDetailModel(int id)
        {
            var _info = await _dbContext.BindServiceImage.Where(x => x.Id == id).AsNoTracking().FirstOrDefaultAsync();
            if (_info == null || _info == default)
            {
                throw new PasteCodeException("查询的信息不存在，无法执行编辑操作！");
            }
            var dto = ObjectMapper.Map<BindServiceImage, BindServiceImageDto>(_info);
            var _dataModel = PasteBuilderHelper.ReadModelProperty<BindServiceImageDto>(dto);
            return _dataModel;
        }

        /// <summary>
        /// 读取ListDto的数据模型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public VoloModelInfo ReadListModel()
        {
            var _model = PasteBuilderHelper.ReadModelProperty<BindServiceImageListDto>(new BindServiceImageListDto());
            var _query_model = PasteBuilderHelper.ReadModelProperty(new InputSearchBase());
            if (_query_model != null)
            {
                _model.QueryProperties = _query_model.Properties;
            }
            return _model;
        }

        /// <summary>
        /// 按页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public async Task<PagedResultDto<BindServiceImageListDto>> Page([FromQuery]InputSearchBase input)
        {
            var query = _dbContext.BindServiceImage.Where(t => 1 == 1).OrderByDescending(x=>x.Id);
            var _pagedto = new PagedResultDto<BindServiceImageListDto>();
            _pagedto.TotalCount = await query.CountAsync();
            var userList = await query.Page(input.page, input.size).ToListAsync();
            var temList = ObjectMapper.Map<List<BindServiceImage>, List<BindServiceImageListDto>>(userList);
            _pagedto.Items = temList;
            return _pagedto;
        }    }
}
